<!-- templates/pagination.html -->
{% if total_pages > 1 %}
<nav aria-label="Page navigation">
    {% set max_display = 5 %}
    {% set half = (max_display // 2) %}
    {% set start = [1, page - half] | max %}
    {% set end = [start + max_display - 1, total_pages] | min %}
    {% if end < start + max_display - 1 %}
        {% set start = [1, end - max_display + 1] | max %}
    {% endif %}

    <ul class="pagination justify-content-center">
        <!-- 上一页 -->
        {% if page > 1 %}
            <li class="page-item"><a class="page-link" href="{{ url_for('index', page=page-1, search=request.args.get('search'), field=request.args.get('field')) }}">上一页</a></li>
        {% else %}
            <li class="page-item disabled"><span class="page-link">上一页</span></li>
        {% endif %}

        <!-- 第一页 -->
        {% if start > 1 %}
            <li class="page-item"><a class="page-link" href="{{ url_for('index', page=1, search=request.args.get('search'), field=request.args.get('field')) }}">1</a></li>
            {% if start > 2 %}
                <li class="page-item disabled"><span class="page-link">...</span></li>
            {% endif %}
        {% endif %}

        <!-- 中间页码 -->
        {% for p in range(start, end + 1) %}
            <li class="page-item {% if p == page %}active{% endif %}">
                <a class="page-link" href="{{ url_for('index', page=p, search=request.args.get('search'), field=request.args.get('field')) }}">{{ p }}</a>
            </li>
        {% endfor %}

        <!-- 最后一页 -->
        {% if end < total_pages %}
            {% if end < total_pages - 1 %}
                <li class="page-item disabled"><span class="page-link">...</span></li>
            {% endif %}
            <li class="page-item"><a class="page-link" href="{{ url_for('index', page=total_pages, search=request.args.get('search'), field=request.args.get('field')) }}">{{ total_pages }}</a></li>
        {% endif %}

        <!-- 下一页 -->
        {% if page < total_pages %}
            <li class="page-item"><a class="page-link" href="{{ url_for('index', page=page+1, search=request.args.get('search'), field=request.args.get('field')) }}">下一页</a></li>
        {% else %}
            <li class="page-item disabled"><span class="page-link">下一页</span></li>
        {% endif %}
    </ul>
</nav>

<!-- 跳转到指定页码 -->
<div class="page-jump mt-3">
    <form action="{{ url_for('index') }}" method="get" class="form-inline">
        <label for="page-number" class="mr-2">跳转到：</label>
        <input type="number" id="page-number" name="page" class="form-control form-control-sm" min="1" max="{{ total_pages }}" required />
        <button type="submit" class="btn btn-primary btn-sm ml-2">跳转</button>
    </form>
</div>
{% endif %}